package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.sso.entity.User;
import com.tanhua.sso.mapper.UserMapper;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description AUTO
 * @ClassName UserService
 * @Author ZhengXinjie
 * @date 2021.02.06 14:25
 */
@Service
@Slf4j
public class UserService {

    private final RedisTemplate<String, String> redisTemplate;
    private final RocketMQTemplate rocketMQTemplate;
    private final UserMapper userMapper;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    public UserService(RedisTemplate<String, String> redisTemplate, RocketMQTemplate rocketMQTemplate, UserMapper userMapper) {
        this.redisTemplate = redisTemplate;
        this.rocketMQTemplate = rocketMQTemplate;
        this.userMapper = userMapper;
    }


    /**
     * 用户登录
     *
     * @param phone            手机号
     * @param verificationCode 验证码
     * @return token + isNew
     */
    public String login(String phone, String verificationCode) {
        // 获取验证码
        String redisKey = "CHECK_CODE_" + phone;
        boolean isNew = false;

        String redisData = redisTemplate.opsForValue().get(redisKey);
        if (!StringUtils.equals(redisData, verificationCode)) {
            // 验证码错误
            return null;
        }

        // 验证码如果成功, 删除此验证码
        redisTemplate.delete(redisKey);
        // 判断此用户是否是新用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", phone);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            // 新用户需要将信息存储到数据库中
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            userMapper.insert(user);
            isNew = true;
        }
        // 生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());

        String token = Jwts.builder()
                .setClaims(claims) //payload，存放数据的位置，不能放置敏感数据，如：密码等
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                .setExpiration(new DateTime().plusHours(12).toDate()) //设置过期时间，12h后过期
                .compact();

        // 给用户发送登录成功的信息
        try {
            Map<String, Object> msg = new HashMap<>();
            msg.put("id", user.getId());
            msg.put("date", System.currentTimeMillis());
            rocketMQTemplate.convertAndSend("tanhua-sso-login", msg);
        } catch (MessagingException e) {
            log.error("发送信息失败!", e);
        }


        return token + "|" + isNew;
    }

    /**
     * 查询token对应的用户
     * @param token
     * @return
     */
    public User queryUserByToken(String token) {
        try {
            Map<String, Object> body = Jwts.parser().setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
            User user = new User();
            // 生成token的时候存储了id
            user.setId(Long.valueOf(body.get("id").toString()));

            // 查询用户的手机

            String redisKey = "TANHUA_USER_MOBILE_" + user.getId();
            // 判断redis中是否存在此id
            if (this.redisTemplate.hasKey(redisKey)) {
                String mobile = redisTemplate.opsForValue().get(redisKey);
                user.setMobile(mobile);
            } else {
                // 查询数据库
                User u = userMapper.selectById(user.getId());
                user.setMobile(u.getMobile());

                // 将手机号存入到redis中, 并设置超时时间
                long timeout = Long.valueOf(body.get("exp").toString()) * 1000 - System.currentTimeMillis();
                redisTemplate.opsForValue().set(redisKey, u.getMobile(), timeout, TimeUnit.MILLISECONDS);
            }
            return user;
        } catch (ExpiredJwtException e) {
            log.info("token已经过期！ token = " + token);
        } catch (Exception e) {
            log.error("token不合法！ token = " + token, e);
        }
        return null;
    }
}

